#include <CoOS.h>			                 /*!< CoOS header file            */
#include <stdio.h>
#include "NUC123.h"

U8 u8Plus = 0;
U32 u32Dismm = 0;

void GPF3_IRQ(void)
{
	if(GPIO_GET_INT_FLAG(PF, BIT3))
	{
		GPIO_CLR_INT_FLAG(PF, BIT3);
		if(u8Plus == 0)
		{
			TIMER_Start(TIMER1);
			u8Plus = 1;
		}
		else if(u8Plus == 1)
		{
			U32 u32Dis = TIMER_GetCounter(TIMER1);
			GPIO_DisableInt(PF, 3);
			TIMER_Stop(TIMER1);	
			u32Dismm =u32Dis*170/1000;			
			u8Plus = 2;
		}
	}
}

void SR04_Init()
{
	GPIO_SetMode(PF, BIT2, GPIO_PMD_OUTPUT);
	GPIO_SetMode(PF, BIT3, GPIO_PMD_INPUT);
	PF2 = 0;
}

void SR04_Trigger()
{
	GPIO_EnableInt(PF, 3, GPIO_INT_BOTH_EDGE);
	NVIC_EnableIRQ(GPCDF_IRQn);

	TIMER_Open(TIMER1, TIMER_ONESHOT_MODE, 1);
	TIMER_ClearIntFlag(TIMER1);
	TIMER_ClearWakeupFlag(TIMER1);
	
	TIMER_SET_PRESCALE_VALUE(TIMER1, 11);
	TIMER_SET_CMP_VALUE(TIMER1, 1000000);
	
	PF2 = 1;	
	u8Plus = 0;
	CoTickDelay(1);
	PF2 = 0;	
}

U32 SR04_GetDistance(void)
{
	if(u8Plus != 2)
	{
		return 0;
	}

	return u32Dismm;
}

